package cn.test.protocol;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Autowired;

import com.hrm.service.PeopleService;
import com.hrm.websocket.WebSocketServer;
import com.hrm.websocket.WebSocketSession;

import cn.test.entity.Friend;
import cn.test.entity.Group;
import cn.test.entity.People;
@SuppressWarnings("unchecked")
public class ProtocolImpl {
	private static final Log log = LogFactory.getLog(ProtocolImpl.class);
	private static final String retCode = "retCode";
	private static final String ret = "ret";
	@Autowired
	private PeopleService peopleService;
	public PeopleService getPeopleService() {
		return peopleService;
	}

	public void setPeopleService(PeopleService peopleService) {
		this.peopleService = peopleService;
	}

	// {"type":1,"method":"getValidCode","timestamp":1339744568758}
	public String parse(String msg, WebSocketSession session) {
		
//		System.out.println("receiv msg : " + msg);
		log.debug(msg);
		JSONObject jo = parseJSONObject(msg);
		Object o = jo.get("type");
		int typeCode = Integer.parseInt(o.toString());
		switch (typeCode) {
		case 0:
			break;
		case 1:
			// LOGIN
			return login(jo, session);
		case 2:
			return chart(jo, session);
		case 3:
			return upload(jo, session);
		default:
			break;
		}
		return null;
	}

	public String chart(JSONObject jo, WebSocketSession session) {
		String method = jo.get("method").toString();
		if ("send".equals(method)) {
			String to = jo.get("to").toString();
			WebSocketSession toSession = WebSocketServer.findSessionByPid(to);
			if (toSession == null) {
				jo.put(retCode, "0");
				jo.put(ret, "people not login");
				session.getOffLineMessage().add(jo);
			} else {
				toSession.send(jo.toJSONString().getBytes());
			}
		}else if("shake".equals(method)){
			String to = jo.get("to").toString();
			WebSocketSession toSession = WebSocketServer.findSessionByPid(to);
			if (toSession == null) {
				jo.put(retCode, "0");
				jo.put(ret, "people not login");
				session.getOffLineMessage().add(jo);
			} else {
				toSession.send(jo.toJSONString().getBytes());
			}
		}
		return jo.toJSONString();
	}
	
	public String upload(JSONObject jo, WebSocketSession session) {
		String method = jo.get("method").toString();
		if ("upload".equals(method)) {
			if(jo.get("state")!=null&&"success".equals(jo.get("state").toString())){
				return jo.toJSONString();
			}
			String fileName = jo.get("fileName").toString();
			String filePath=getUploadFilePath()+"/"+fileName;
			session.setFilePath(filePath);
			session.setFileName(fileName);
			session.setJo(jo);
			session.setUploadFileSize(Long.parseLong(jo.get("fileSize").toString()));//获取上传文件总大小
			//手工设置session的buffer大小
			session.setReadBuffer(ByteBuffer.allocate(1024*1024*1));//4M的大小
			jo.put("state", "ready");
			jo.put("uploadProgress", "begin");
		}else if("talk".equals(method)){
			if(jo.get("state")!=null&&"success".equals(jo.get("state").toString())){//如果上传成功，则发送消息到原来的地方
				return jo.toJSONString();
			}
			String fileName = jo.get("fileName").toString();
			String from=jo.get("from").toString();
			String[] tmp=fileName.split("\\.");
			String filePath=getImgTmpFilePath()+"/"+generateFileName(from)+"."+tmp[tmp.length-1];
			session.setFilePath(filePath);
			session.setJo(jo);
			jo.put("state", "ready");
			session.setUploadFileSize(Long.parseLong(jo.get("fileSize").toString()));//获取上传文件总大小
			jo.put("uploadProgress", "begin");
		}else if("deliver".equals(method)){
			if(jo.get("state")!=null&&"success".equals(jo.get("state").toString())){
				String to = jo.get("to").toString();
				WebSocketSession toSession = WebSocketServer.findSessionByPid(to);
				if (toSession == null) {
					jo.put(retCode, "0");
					jo.put(ret, "people not login");
					session.getOffLineMessage().add(jo);
				} else {
					toSession.send(jo.toJSONString().getBytes());
				}
				return jo.toJSONString();
			}
			String fileName = jo.get("fileName").toString();
			String from=jo.get("from").toString();
			String[] tmp=fileName.split("\\.");
			String filePath=getUploadFilePath()+"/"+generateFileName(from)+"."+tmp[tmp.length-1];
			session.setFilePath(filePath);
			session.setJo(jo);
			jo.put("state", "ready");
		}
		return jo.toJSONString();
	}
	
	public String login(JSONObject jo, WebSocketSession session) {
		String method = jo.get("method").toString();
		String[] retArray = new String[2];
		if ("getValidCode".equals(method)) {
			String validCode = "" + (int) (Math.random() * 10)
					+ (int) (Math.random() * 10) + (int) (Math.random() * 10)
					+ (int) (Math.random() * 10);
			session.setValidCode(validCode);
			jo.put(retCode, "1");
			jo.put(ret, validCode);
		} else if ("login".equals(method)) {
			String pid = jo.get("pid").toString();
			String pwd = jo.get("pwd").toString();
			String validCode = jo.get("validCode").toString();
			retArray[0] = "0";
			if (session.getValidCode().equals(validCode) && validUser(pid, pwd)) {
				jo.put(retCode, "1");
				jo.put(ret, "true");
//				jo.put("people", peopleInit(pid));
				jo.put("people", peopleService.login(Integer.parseInt(pid)));
				session.setPid(pid);
			} else {
				jo.put(retCode, "0");
				jo.put(ret, "false");
			}
		} else {
			jo.put(retCode, "0");
			jo.put(ret, "method error");
		}
		return jo.toJSONString();
	}


	private boolean validUser(String pid, String pwd) {
		return true;
	}

	public JSONObject parseJSONObject(String jsonStr) {
		Object o = null;
		try {
			o = new JSONParser().parse(jsonStr);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
		if (o != null) {
			JSONObject jObj = (JSONObject) o;
			return jObj;
		}
		return null;
	}

	public static void main(String[] args) {
	}
	private String getUploadFilePath(){
		String tmp = this.getClass().getResource("/").getPath();
		String fileFolderPath=tmp.substring(0,tmp.indexOf("WEB-INF"))+"upload";
		File file = new File(fileFolderPath);
		if(!file.exists()){
			file.mkdir();
		}
		return fileFolderPath;
	}
	private String getImgTmpFilePath(){
		String tmp = this.getClass().getResource("/").getPath();
		String fileFolderPath=tmp.substring(0,tmp.indexOf("WEB-INF"))+"tmp";
		File file = new File(fileFolderPath);
		if(!file.exists()){
			file.mkdir();
		}
		return fileFolderPath;
	}
	public static boolean saveFileFromBytes(byte[] b, String outputFile)  
     {  
       BufferedOutputStream stream = null;  
       File file = null;  
       try  
       {  
         file = new File(outputFile);  
         FileOutputStream fstream = new FileOutputStream(file);  
         stream = new BufferedOutputStream(fstream);  
         stream.write(b);  
       }  
       catch (Exception e)  
       {  
         e.printStackTrace();
         return false;
       }  
       finally  
       {  
         if (stream != null)  
         {  
           try  
           {  
             stream.close();  
           }  
           catch (IOException e1)  
           {  
             e1.printStackTrace();  
           }  
         }  
       }  
       return true;  
     }  
	 private String generateFileName(String from){//图片上传缓存文件名为用户id+当前时间
		 return from+new Date().getTime();
	 }
}
